package com.example.interceptor;

import com.example.ErrorEnum;
import com.example.base.DemoContext;
import com.example.base.DemoException;
import com.example.contanxt.Context;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import reactor.util.annotation.NonNull;

public class PhoneInterceptor implements HandlerInterceptor {

    private final Logger log = LoggerFactory.getLogger(PhoneInterceptor.class);

    @SuppressWarnings("null")
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if(!StringUtils.hasLength(request.getHeader(Context.HEAD_PHONE))){
            throw new DemoException(ErrorEnum.LACK_PHONE.getCode(), ErrorEnum.LACK_PHONE.getMessage());
        }
        request.setAttribute(Context.HEAD_PHONE,request.getHeader(Context.HEAD_PHONE));
        DemoContext.setPhone(request.getHeader(Context.HEAD_PHONE));
        return true;
    }

    @SuppressWarnings("null")
    public void postHandle(@NonNull HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @SuppressWarnings("null")
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        log.info("当前用户调用完成前，上下文的手机号为：{}",DemoContext.getPhone());
        DemoContext.clearPhone();
        log.info("当前用户调用完成后，上下文的手机号为：{}",DemoContext.getPhone());
    }
}
